<?php


namespace app\db\admin;

use app\table\CmsTable;
use app\utils\encrypt\Hash_pbkdf2;
use yifang\db\Db_raw;

//管理员操作表
class D_memberAdmin
{

    /**
     * 信息格式化
     */
    private function detailed($Result, $format)
    {

        //  是否显示
        if (isset($Result['status'])) {
            $statusMap = array();
            $statusMap["1"] = "启用";
            $statusMap["2"] = "禁用";
            $Result['statusFormat'] = isset($statusMap[$Result['status']]) ? $statusMap[$Result['status']] : "---";
        }

        // 返回结果
        return $Result;
    }

    /** 直接使用sql时使用,带表前缀
     * @return string
     */
    private function getTableName(): string
    {
        return CmsTable::member_admin();
    }

    /**获取管理员信息
     * @param $paramObj
     * @return array
     */
    public function info($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数
            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'id' => 'require|number',
                'field' => ''

            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();
            $dataDefault["field"] = "*";
            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where[] = array(
                "id", "=", $dataObj->request->id
            );

            try {
                $ret = Db()->name(CmsTable::member_admin())->field($dataObj->request->field)->where($where)->find();
                if (count($ret) == 0) {
                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_NOTICE, app("errorCode")::DATA_NOT_EXIST, "数据不存在");
                } else {
                    $final_arr["result"] = $ret; //返回信息放入结果
                }
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**获取管理员信息通过user
     * @param $paramObj
     * @return array
     */
    public function getUser($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'user' => 'require',
                'field' => ''
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();
            $dataDefault["field"] = "*";
            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where[] = array(
                "user", "=", $dataObj->request->user
            );
            try {
                $ret = Db()->name(CmsTable::member_admin())->field($dataObj->request->field)->where($where)->find();
                if (count($ret) == 0) {
                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_NOTICE, app("errorCode")::DATA_NOT_EXIST, "数据不存在");
                } else {
                    $final_arr["result"] = $ret; //返回信息放入结果
                }
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**添加信息
     * @param $paramObj
     * @return array
     */
    public function store($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'user' => '',
                'password' => '',
                'status' => '',
                'roleId' => 'must|number',
            ));

            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array(
                'status' => 1,
            );


            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作


        if ($final_arr["error_no"] == 0) {

            $data = array(
                "user" => $dataObj->request->user,
                "password" => Hash_pbkdf2::encrypt($dataObj->request->password),
                "status" => $dataObj->request->status,
                "roleId" => $dataObj->request->roleId,
            );

            try {
                $result = Db()->name(CmsTable::member_admin())->insert($data);
                $final_arr["result"] = $result; //返回信息放入结果
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**修改信息
     * @param $paramObj
     * @return array
     */
    public function update($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求 校验后的数据,包括默认值都会放这里
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'id' => '',
                'password' => 'must|password',
                'status' => '',
                'roleId' => 'must|number',
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where[] = array(
                "id", "=", $dataObj->request->id
            );
            $data = array(
                "status" => $dataObj->request->status,
                "roleId" => $dataObj->request->roleId,
            );
            if ($dataObj->request->password != "") { //如果为空不修改
                $data["password"] = Hash_pbkdf2::encrypt($dataObj->request->password);
            }


            try {
                $result = Db()->name(CmsTable::member_admin())->where($where)->update($data);
                $final_arr["result"] = $result; //返回信息放入结果
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**批量删除
     * @param $paramObj
     * @return array
     */
    public function delete($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求 校验后的数据,包括默认值都会放这里
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'id' => 'require',
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            //判断 id是否为数组,如果是数组,返回id数组,如果不是数组,返回单成员数组
            $ids = is_array($dataObj->request->id) ? $dataObj->request->id : explode(",", $dataObj->request->id);
            $condition = array();
            $condition[] = array(
                "id", "in", $ids
            );

            try {
                $result = Db()->name(CmsTable::member_admin())->where($condition)->delete();
                $final_arr["result"] = $result; //返回信息放入结果
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**
     * 获取数据
     * @param string $paramObj
     */
    public function getData($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = array();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'field' => '',
            );
            $dataDefault = array();
            $dataDefault["field"] = "*";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            try {
                $final_arr["result"] = Db()->name(app("cmsTable")::member_admin())->field($dataObj->request->field)->select();
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**
     * 列表数据
     * @param string $paramObj
     */
    public function listData($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = array();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'order' => '',
                "type" => "",
                "keyword" => "",
                "status" => "",
                "roleId" => "",
                'field' => '',
                'format' => '',
            );
            $dataDefault = array(
                'order' => '1',
            );
            $dataDefault["field"] = "*";
            $dataDefault["format"] = "1";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $condition = array();
            if ($dataObj->request->status > 0) {
                $condition[] = array(
                    "status", "=", $dataObj->request->status
                );
            }
            if ($dataObj->request->roleId > 0) {
                $condition[] = ["roleId", "=", $dataObj->request->roleId];
            }
            if ($dataObj->request->keyword ) {
                switch ($dataObj->request->type) {
                    case 0:     //搜索用户名
                        $raw=new Db_raw();
                        $raw->setContent("LOCATE('{$dataObj->request->keyword}',`user`)");
                        $condition[] = array(
                            $raw, ">", 0
                        );
                        break;
                }
            }
            //处理 排序  设置默认0
            $sortColumn = "id";
            $sortDirection = $dataObj->request->order % 2 === 1 ? "ASC" : "DESC";   //单数升序 双数降序 0也为降序

            switch ($dataObj->request->order) {
                case 1:
                case 2:  // id 升序
                    $sortColumn = "id";
                    break;
            }

            try {
                $result = Db()->name(app("cmsTable")::member_admin())->order($sortColumn, $sortDirection)->field($dataObj->request->field)->where($condition)->paginate();
                if ($result && $result["data"]) {
                    foreach ($result["data"] as $key => $val) {
                        if ($dataObj->request->format) {
                            $result["data"][$key] = $this->detailed($val, $dataObj->request->format);
                        }
                    }
                }
                $final_arr["result"] = $result;
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**设置管理员角色
     * @param $paramObj
     * @return array
     */
    public function setRole($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'id' => 'require|number',
                'roleId' => 'require|number'
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where[] = array(
                "id", "=", $dataObj->request->id
            );
            $data = ["roleId" => $dataObj->request->roleId];

            try {
                $ret = Db()->name(CmsTable::member_admin())->where($where)->update($data);
                $final_arr["result"] = $ret;
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**设置管理员状态
     * @param $paramObj
     * @return array
     */
    public function setStatus($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'id' => 'require|number',
                'Status' => 'require|between:1,2'
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where[] = array(
                "id", "=", $dataObj->request->id
            );
            $data = ["status" => $dataObj->request->status];

            try {
                $ret = Db()->name(CmsTable::member_admin())->where($where)->update($data);
                $final_arr["result"] = $ret;
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**设置新密码
     * @param $paramObj
     * @return array
     */
    public function setPassword($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'id' => 'require|number',
                'newPassword' => 'require|password'
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();
            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where[] = array(
                "id", "=", $dataObj->request->id
            );
            $data = ["password" => Hash_pbkdf2::encrypt($dataObj->request->newPassword)];

            try {
                $ret = Db()->name(CmsTable::member_admin())->where($where)->update($data);
                $final_arr["result"] = $ret;
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }
}